package org.example.aienglishapp.controller.speech.dialoguebook;

import org.example.aienglishapp.entity.speech.dialoguebook.DialogueBook;
import org.example.aienglishapp.mapper.speech.dialoguebook.DialogueBookMapper;
import org.example.aienglishapp.util.response.ResponseResult;
import org.example.aienglishapp.util.response.ResultCode;
import org.example.aienglishapp.dto.speech.dialoguebook.DialogueBookDTO;
import org.example.aienglishapp.service.speech.dialoguebook.DialogueBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.sql.Blob;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/books")
public class DialogueBookController {

    private static final Logger logger = LoggerFactory.getLogger(DialogueBookController.class);

    @Autowired
    private DialogueBookMapper dialogueBookMapper;

    @Autowired
    @Qualifier("speechRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DialogueBookService dialogueBookService;

    private static final String CACHE_KEY_PREFIX = "book:";

    @GetMapping("/{id}")
    public ResponseResult<DialogueBookDTO> getBookById(@PathVariable Long id) {
        try {
            logger.info("Fetching book with ID: {}", id);

            // 尝试从 Redis 中获取书籍信息
            String key = CACHE_KEY_PREFIX + id;
            DialogueBook book = (DialogueBook) redisTemplate.opsForValue().get(key);

            if (book == null) {
                logger.info("Book not found in Redis, fetching from database");
                // 如果 Redis 中没有，从数据库中获取
                book = dialogueBookMapper.findById(id);
                if (book != null) {
                    // 将书籍信息存储到 Redis
                    redisTemplate.opsForValue().set(key, book);
                } else {
                    logger.warn("Book with ID {} not found in the database", id);
                    return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "书籍不存在");
                }
            }

            // 从数据库获取图片数据
            Blob picture = dialogueBookService.getBookPictureById(id);

            // 转换为 DTO
            logger.info("Converting book to DTO");
            DialogueBookDTO bookDTO = new DialogueBookDTO(book.getBookId(), book.getTitle(), book.getDescription(), picture);
            return ResponseResult.success(bookDTO);
        } catch (Exception e) {
            logger.error("Error while fetching book with ID: {}", id, e);
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "内部服务器错误");
        }
    }

    @GetMapping
    public ResponseResult<List<DialogueBookDTO>> getAllBooks() {
        List<DialogueBook> books = dialogueBookMapper.findAll();
        // 转换为 DTO 列表
        List<DialogueBookDTO> bookDTOs = books.stream()
                .map(b -> new DialogueBookDTO(b.getBookId(), b.getTitle(), b.getDescription(), b.getPicture()))
                .collect(Collectors.toList());
        return ResponseResult.success(bookDTOs);
    }

    @PostMapping
    public ResponseResult<Integer> createBook(@RequestBody DialogueBook book) {
        int result = dialogueBookMapper.insert(book);
        if (result > 0) {
            // 将书籍信息存储到 Redis
            String key = CACHE_KEY_PREFIX + book.getBookId();
            redisTemplate.opsForValue().set(key, book);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "创建书籍失败");
        }
    }

    @PutMapping
    public ResponseResult<Integer> updateBook(@RequestBody DialogueBook book) {
        int result = dialogueBookMapper.update(book);
        if (result > 0) {
            // 更新 Redis 中的书籍信息
            String key = CACHE_KEY_PREFIX + book.getBookId();
            redisTemplate.opsForValue().set(key, book);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "更新书籍失败");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Integer> deleteBook(@PathVariable Long id) {
        int result = dialogueBookMapper.deleteById(id);
        if (result > 0) {
            // 删除 Redis 中的书籍信息
            String key = CACHE_KEY_PREFIX + id;
            redisTemplate.delete(key);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "删除书籍失败");
        }
    }
}